# 导入utils.getPublicData.py文件下的所有数据和方法
from utils.getPublicData import *
# 让地址往前两个父级目录
import sys
sys.path.append('..')
from word_cloud import *

# 获取地图数据
def getHomeGeoChartData(house_data):
    # 各个城市平均值
    price_average_dict = average_price(house_data)
    # 循环各个城市是否在cityList['city']中，如果在，就让该省的平均值=找到的某个城市的平均值
    cityDict = {}
    for key, value in price_average_dict.items():
        for i in cityList:
            for j in i['city']:
                if j.find(key) != -1:
                    cityDict[i['province']] = value
    cityDictList = []
    # 转换成地图能够使用的数据类型
    for key, value in cityDict.items():
        cityDictList.append({
            'name': key,
            'value': value
        })
    return cityDictList

# 处理地图数据 -- 取各地区的房屋房价平均值
def average_price(house_data):
    # 各地区房价和房屋数量统计
    city_prices = {}
    city_counts = {}
    for data in house_data:
        city = data.city
        price = int(data.price)
        if city in city_prices:
            city_prices[city] += price
            city_counts[city] += 1
        else:
            city_prices[city] = price
            city_counts[city] = 1
    # 求平均数
    price_average = {}
    for city in city_prices:
        price_average[city] = round(city_prices[city] / city_counts[city] ,1)

    return price_average

# 获取数据 -- 数据标签的数据
def getHomeTagsData(house_data):
    # 数据总量
    totalLen = len(house_data)
    maxPrice = 0
    maxHouseType = {}
    maxHouseSaleStatus = {}
    for data in house_data:
        # 价格最高
        if maxPrice < int(data.price):
            maxPrice = int(data.price)
        # 房屋类型统计
        if maxHouseType.get(data.houseType, -1) == -1:
            maxHouseType[data.houseType] = 1
        else:
            maxHouseType[data.houseType] += 1
        # 售房情况统计
        if maxHouseSaleStatus.get(data.sale_status, -1) == -1:
            maxHouseSaleStatus[data.sale_status] = 1
        else:
            maxHouseSaleStatus[data.sale_status] += 1
    # 房屋类型最多 -- 根据字典键值对进行排序， 以统计个数排序， 并为降序排序（大到小）
    maxHouseTypeSort = list(sorted(maxHouseType.items(), key=lambda x: x[1], reverse=True))
    # 售房情况最多 -- 根据字典键值对进行排序， 以统计个数排序， 并为降序排序（大到小）
    maxHouseSaleStatusSort = list(sorted(maxHouseSaleStatus.items(), key=lambda x: x[1], reverse=True))

    print(maxHouseSaleStatusSort)

    maxHouseSale = ''
    if maxHouseSaleStatusSort[0][0] == '1':
        maxHouseSale = '在售'
    elif maxHouseSaleStatusSort[0][0] == '2':
        maxHouseSale = '已售'
    elif maxHouseSaleStatusSort[0][0] == '3':
        maxHouseSale = '出租中'
    elif maxHouseSaleStatusSort[0][0] == '4':
        maxHouseSale = '已出租'
    elif maxHouseSaleStatusSort[0][0] == '5':
        maxHouseSale = '预售'
    elif maxHouseSaleStatusSort[0][0] == '6':
        maxHouseSale = '其他'

    return totalLen, maxPrice, maxHouseTypeSort[0][0], maxHouseSale

# 获取各城市房源个数数据
def getHomeRadarData(house_data):
    cityDict = {}
    # 词频统计 -- 城市统计
    for i in house_data:
        if cityDict.get(i.city, -1) == -1:
            cityDict[i.city] = 1
        else:
            cityDict[i.city] += 1
    radarOne = []
    for key, value in cityDict.items():
        radarOne.append({
            'name': key,
            'max': 30
        })
    radarTwo = list(cityDict.values())

    return radarOne, radarTwo

# 获取地址词云图数据
def getAddressData():
    targetImg = './static/image/address.png'
    resImg = './static/image/address_cloud.jpg'
    resSrc = get_address_img(targetImg, resImg)
    return resSrc

# 获取搜索页面的post请求数据 - 模糊查询
def getHouseByHouseName(searchWord, house_data):
    searchList = []
    for house in house_data:
        if house.title.find(searchWord) == -1:
            searchList.append(house)
    return searchList

# 获取房价分析页面的各城市价格区间 -- 柱状图
def getPriceChartBar(houseList):
    x = ['0-5000', '5000-10000', '10000-15000', '15000-20000', '20000-25000', '25000-30000', '30000-35000', '35000-']
    y = [0 for x in range(len(x))]
    for h in houseList:
        if int(h.price) <= 4000:
            y[0] += 1
        elif int(h.price) <= 6000:
            y[1] += 1
        elif int(h.price) <= 8000:
            y[2] += 1
        elif int(h.price) <= 10000:
            y[3] += 1
        elif int(h.price) <= 12000:
            y[4] += 1
        elif int(h.price) <= 15000:
            y[5] += 1
        elif int(h.price) <= 18000:
            y[6] += 1
        else:
            y[7] += 1
    return x, y

# 获取房价分析页面的各开盘时间的平均房价 -- 折线图
def getPriceChartLine(houseList):
    open_dateDict = {}
    for h in houseList:
        if open_dateDict.get(h.open_date, -1) == -1:
            open_dateDict[h.open_date] = int(h.price)
        else:
            open_dateDict[h.open_date] += int(h.price)
    return list(open_dateDict.keys()), list(open_dateDict.values())

# 获取房价分析页面的城市总价 -- 散点图
def getPriceChartScatter(houseList):
    data = []
    for h in houseList:
        data.append(
            h.totalPrice_range
        )
    return data

# 获取房型（每一种室、厅的个数）
def getDetailChartTreeSun(house_info):
    rooms_dict = {}
    for house in house_info:
        for room in house.rooms_desc:
            if rooms_dict.get(room, -1) == -1:
                rooms_dict[room] = 1
            else:
                rooms_dict[room] += 1
    result = []
    for key, value in rooms_dict.items():
        result.append({
            'name': key,
            'value': value
        })
    return result

# 获取房屋建面数据
def getDetailChartPie(house_info, defaultType):
    if defaultType == 'big':
        x = ['80-100', '100-110', '110-120', '120-130', '130-140', '140-150', '150-160', '160-n']
        y = [0 for x in range(len(x))]
        for house in house_info:
            try:
                if int(house.area_range[1]) >= 80 and int(house.area_range[1]) <= 100:
                    y[0] += 1
                elif int(house.area_range[1]) <= 110:
                    y[1] += 1
                elif int(house.area_range[1]) <= 120:
                    y[2] += 1
                elif int(house.area_range[1]) <= 130:
                    y[3] += 1
                elif int(house.area_range[1]) <= 140:
                    y[4] += 1
                elif int(house.area_range[1]) <= 150:
                    y[5] += 1
                elif int(house.area_range[1]) <= 160:
                    y[6] += 1
                elif int(house.area_range[1]) > 160:
                    y[7] += 1
            except:
                continue
    elif defaultType == 'small':
        x = ['0-40', '40-60', '60-80', '80-100', '100-120', '120-150', '150-n']
        y = [0 for x in range(len(x))]
        for house in house_info:
            try:
                if int(house.area_range[0]) <= 40:
                    y[0] += 1
                elif int(house.area_range[0]) <= 60:
                    y[1] += 1
                elif int(house.area_range[0]) <= 80:
                    y[2] += 1
                elif int(house.area_range[0]) <= 100:
                    y[3] += 1
                elif int(house.area_range[0]) <= 120:
                    y[4] += 1
                elif int(house.area_range[0]) <= 150:
                    y[5] += 1
                elif int(house.area_range[0]) > 150:
                    y[6] += 1
            except:
                continue
    return x, y

# 获取房屋装修情况、房屋类型数据  /   获取房屋其他分析页面的标签数据
def getDictData(house_info, field):
    resDict = {}
    for house in house_info:
        if field == 'houseDecoration' and house.houseDecoration != '':
            if resDict.get(house.houseDecoration, -1) == -1:
                resDict[house.houseDecoration] = 1
            else:
                resDict[house.houseDecoration] += 1
        elif field == 'houseType' and house.houseType != '':
            if resDict.get(house.houseType, -1) == -1:
                resDict[house.houseType] = 1
            else:
                resDict[house.houseType] += 1
        elif field == 'tags':
            for tag in house.tags:
                if resDict.get(tag, -1) == -1:
                    resDict[tag] = 1
                else:
                    resDict[tag] += 1
    resData = []
    for key, value in resDict.items():
        resData.append({
            'name': key,
            'value': value
        })
    return resData

# 调用函数，并返回
def getTypeChartsData(house_info):
    houseDecorationData = getDictData(house_info, 'houseDecoration')
    houseTypeData = getDictData(house_info, 'houseType')
    return houseDecorationData, houseTypeData

# 获取房屋交房情况数据
def getOtherChartsData(house_info):
    cityDictOne = {}
    cityDictTwo = {}
    for house in house_info:
        if house.on_time == '0000-00-00 00:00:00':
            if cityDictOne.get(house.city, -1) == -1:
                cityDictOne[house.city] = 1
            else:
                cityDictOne[house.city] += 1
        elif house.on_time != '0000-00-00 00:00:00':
            if cityDictTwo.get(house.city, -1) == -1:
                cityDictTwo[house.city] = 1
            else:
                cityDictTwo[house.city] += 1
    return list(cityDictOne.keys()), list(cityDictOne.values()), list(cityDictTwo.values())

# 获取房屋售房情况数据
def getOtherChartsData_Pie(house_info):
    sale_status_dict = {}
    for house in house_info:
        if house.sale_status == '1':
            if sale_status_dict.get('在售', -1) == -1:
                sale_status_dict['在售'] = 1
            else:
                sale_status_dict['在售'] += 1
        elif house.sale_status == '2':
            if sale_status_dict.get('已售', -1) == -1:
                sale_status_dict['已售'] = 1
            else:
                sale_status_dict['已售'] += 1
        elif house.sale_status == '3':
            if sale_status_dict.get('出租中', -1) == -1:
                sale_status_dict['出租中'] = 1
            else:
                sale_status_dict['出租中'] += 1
        elif house.sale_status == '4':
            if sale_status_dict.get('已出租', -1) == -1:
                sale_status_dict['已出租'] = 1
            else:
                sale_status_dict['已出租'] += 1
        elif house.sale_status == '5':
            if sale_status_dict.get('预售', -1) == -1:
                sale_status_dict['预售'] = 1
            else:
                sale_status_dict['预售'] += 1
        elif house.sale_status == '6':
            if sale_status_dict.get('其他', -1) == -1:
                sale_status_dict['其他'] = 1
            else:
                sale_status_dict['其他'] += 1
    resData = []
    for key, value in sale_status_dict.items():
        resData.append({
            'name': key,
            'value': value
        })
    return resData

# 获取房屋标签数据
def getTagsData(house_info):
    tagsData = getDictData(house_info, 'tags')
    return [x['name'] for x in tagsData], [x['value'] for x in tagsData]